import type { Directive, DirectiveBinding } from "vue";

/**
 * 给元素或随机背景图
 * 随机：v-randomBgImg
 */
const randomBgImg: Directive = {
    mounted(el: HTMLElement, _binding: DirectiveBinding) {
        const { width, height } = el.getBoundingClientRect();

        const picWidth = Math.ceil(width) + 20;
        const picHeight = Math.ceil(height) + 20;

        const styleObj: Partial<CSSStyleDeclaration> = {
            backgroundImage: `url(https://picsum.photos/${picWidth}/${picHeight}?random=${Math.random() * Date.now()})`,
            // backgroundImage: `url(https://source.unsplash.com/1600x900/?nature)`,
            backgroundRepeat: "no-repeat",
            backgroundSize: "cover",
            // backgroundAttachment: "fixed",
            backgroundPosition: "center"
        };
        // el.style = styleObj; // 无法为“style”赋值，因为它是只读属性。
        Object.assign(el.style, styleObj);
    }
};

export default randomBgImg;
